import { useMemo, useCallback } from "react";
import i18n from "i18n-js";
import { Image, Text, View, Progress } from "@tarojs/components";
import { GStyleSheet, DynamicColors } from "@/utils/DarkMode";
import { getItemForPk } from '@/config/product';
import { INewDevice } from '@/models/deviceList/deviceCapacity';
import DeviceDataModel from '@/models/deviceData';
import arrowIcon from '@/assets/images/home_icon_arrow.png';
import shareIcon from '@/assets/images/device-share.png';
import CapacityView from './CapacityView';



const dstyle = GStyleSheet.create({
  container: {
    padding: 20,
    borderRadius: 10,
    marginBottom: 20,
    backgroundColor: DynamicColors.cardBackgroundColor,
    position: 'relative'
  },
  name: {
    color: DynamicColors.normalTextColor,
    fontSize: 16,
    height: 22,
    lineHeight: '22px',
    wordBreak: 'break-all'
  },
  statusName: {
    fontSize: 13,
    height: 22,
    lineHeight: '22px',
    color: DynamicColors.normalTextGaryColor,
  },
  statusText: {
    color: DynamicColors.normalTextGaryColor,
  },
  onlineText: {
    color: DynamicColors.normalTextColor,
  },
  icon: {
    width: 50,
    height: 50,
    marginRight: 10,
    borderRadius: 10,
  },
  arrowView: {
    marginLeft: 20
  },
  arrowIcon: {
    width: 25,
    height: 25,
  },
  stateView: {
    justifyContent: 'flex-end',
  },
  bleStateView: {
    justifyContent: 'flex-start',
  },
  shareIcon: {
    width: 23,
    height: 19,
    position: 'absolute',
    top: 0,
    left: 0,
  },
  quotaContainer: {
    width: '100%',
  },
  quotaInfo: {
    display: 'flex',
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 4,
  },
  quotaText: {
    fontSize: 12,
    color: DynamicColors.normalTextGaryColor,
  },
  quotaValue: {
    fontSize: 12,
    color: DynamicColors.normalTextColor,
  },
  progressBar: {
    width: '100%',
  }
});

interface IProps {
  device: INewDevice;
  renderRight?: any;
  style?: any;
  isShare: boolean;
  showQuotaDetail?: boolean;
  onClick?: () => void;
}


const DeviceItem = ({ device, renderRight, isShare, style, onClick, showQuotaDetail = false }: IProps) => {
  const styles = dstyle.useDynamicStyle();

  const productInfo = useMemo(() => {
    return getItemForPk(device.productKey) || {};
  }, [device.productKey]);

  console.log('productInfo', productInfo, device)
  const icon = useMemo(() => {
    let statusIcon = productInfo.icon;
    if (productInfo.offlineIcon && !device.isOnline) {
      statusIcon = productInfo.offlineIcon;
    }
    return statusIcon;
  }, [device.isOnline, productInfo]);

  const goToDevicePage = useCallback(async () => {
    DeviceDataModel.goToDetailPage(device)
  }, [device]);

  const nameStyle = useMemo(() => {
    if (device.bleCapacity && device.wifiCapacity) {
      // 预留显示两个能力图标
      return { width: '240rpx' }
    }
    // 预留显示一个能力图标
    return { width: '300rpx' }
  }, [device.bleCapacity, device.wifiCapacity])

  console.log('DeviceItem', device);

  const formatMinutes = (minutes: number) => {
    // const hours = Math.floor(minutes / 60);
    // const days = Math.floor(hours / 24);
    
    // if (days > 0) {
    //   return `${days}天`;
    // }
    // if (hours > 0) {
    //   return `${hours}小时`;
    // }
    return `${parseInt(minutes / 60)}分钟`;
  };

  const getQuotaProgress = () => {
    if (!device.quota) return 0;
    return (device.used_quota / device.quota) * 100;
  };

  const getUsedQuota = () => {
    return device.used_quota;
  };

  return (
    <View style={{...styles.container, ...style}} className='centerFlex' onClick={onClick ? onClick : goToDevicePage}>
      {isShare && (
        <Image src={shareIcon} style={styles.shareIcon} />
      )}
      <View style={styles.icon} >
        <Image src={icon} style={styles.icon} mode='aspectFit' />
      </View>
      <View style={{ flex: 1 }}>
        <View style={nameStyle}>
          <Text style={styles.name}>{device.name}</Text>
          {/* {(!renderRight && !device.bleCapacity) && <View>
            <Text style={styles.statusName} className='ellipsisText'>{device.isOnline ? i18n.t('ONLINE') : i18n.t('OFFLINE')}</Text>
          </View>} */}
          {(!renderRight) && <View>
            <Text style={styles.statusName} className='ellipsisText'>{device.isOnline ? i18n.t('ONLINE') : i18n.t('OFFLINE')}</Text>
          </View>}
        </View>
        
        {device?.quota >= 0 && (
          <View style={styles.quotaContainer}>
            <View style={styles.quotaInfo}>
              <Text style={styles.quotaText}>
                已使用
                {
                  showQuotaDetail == false ? (
                    <Text>:{formatMinutes(getUsedQuota())}</Text>
                  ): null
                }
              </Text>
              {
                  showQuotaDetail == true ? (
                    <Text style={styles.quotaValue}>
                      <Text>{formatMinutes(getUsedQuota())} / {formatMinutes(device.quota)}</Text>
                    </Text>
                  ) : null
              }
            </View>
            {
              showQuotaDetail && (
                <Progress
                  percent={getQuotaProgress()}
                  strokeWidth={6}
                  borderRadius={10}
                  color={DynamicColors.tintColor.value}
                  style={styles.progressBar}
                />
              )
            }
            
          </View>
        )}
      </View>
      {renderRight ? renderRight : <View className='centerFlex' style={styles.stateView}>
        {/* <CapacityView device={device} /> */}
        <View style={styles.arrowView}>
        <Image src={arrowIcon} style={styles.arrowIcon} />
        </View>
      </View>}
    </View>
  );
};

export default DeviceItem;
